"""
Copyright 2012 Jorge Novaes Jr.
Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
"""

import urllib
import json
import time
import os
import re
import mmap
import sys

#global variables
_sessionId = ""

def init():
    cookieDBFilename = os.path.join(os.environ['USERPROFILE'], "AppData/Local/Google/Chrome/User Data/Default/Cookies")
    cookieKey = "kongregate.ninjawarz.brokenbulbstudios.comPHPSESSID"
    f = open(cookieDBFilename, 'r+b')
    mf = mmap.mmap(f.fileno(), 0)
    mf.seek(0) # reset file cursor
    m = re.search(cookieKey+'\w+', mf)

    mf.seek(m.start()+len(cookieKey)) # reset file cursor
    global _sessionId
    _sessionId = mf.read(m.end() - m.start() -len(cookieKey))
    mf.close()
    f.close()

    return getMyStats()

def getMyStats():
    params = {"PHPSESSID": _sessionId}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com/ajax/me"
    response = urllib.urlopen(url, query)
    try:
        return json.load(response)
    except ValueError:
        print response.read()
        response.close()
        print ">>> Time error occurred: %s" % (time.strftime("%a, %d %b %Y %H:%M", time.localtime()))
        sys.exit(0)

def heal():
    params = {"PHPSESSID": _sessionId}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com/ajax/hospital"
    return json.load(urllib.urlopen(url, query))

#to fight zumbi horde use "horde" as opponent
def fight(player):
    params = {"PHPSESSID": _sessionId, "opponent": player}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/fight"
    return json.load(urllib.urlopen(url, query))
                
def getOpponents(level=0):
    params = {"PHPSESSID": _sessionId}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/get_opponents/"+str(level)+"/0/50"
    return json.load(urllib.urlopen(url, query))

def unequip(ninja):
    params = {"PHPSESSID": _sessionId, "nid": ninja}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/unequip_weapon"
    return json.load(urllib.urlopen(url, query))
    
def equip(ninja, weapon):
    params = {"PHPSESSID": _sessionId, "iid": weapon, "nid": ninja}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/equip_weapon"
    return json.load(urllib.urlopen(url, query))

def train(ninja):
    params = {"PHPSESSID": _sessionId, "nid": ninja}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/train_ninja"
    return json.load(urllib.urlopen(url, query))

def unequipRelic(slot, relic):
    params = {"PHPSESSID": _sessionId, "slot": slot, "iid": relic}
    query = urllib.urlencode(params)
    url = "    http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/unequip_relic"
    return json.load(urllib.urlopen(url, query))

def equipRelic(slot, relic):
    params = {"PHPSESSID": _sessionId, "slot": slot, "iid": relic}
    query = urllib.urlencode(params)
    url = "    http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/equip_relic"
    return json.load(urllib.urlopen(url, query))
    
def listRelicShop():
    params = {"PHPSESSID": _sessionId}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/shop_inventory/relic"
    return json.load(urllib.urlopen(url, query))

def listWeaponShop():
    params = {"PHPSESSID": _sessionId}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/shop_inventory/weapon"
    return json.load(urllib.urlopen(url, query))

def sellItem(item):
    params = {"PHPSESSID": _sessionId, "iid": item}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/sell_item"
    try:
        ret = json.load(urllib.urlopen(url, query))
    except ValueError:
        ret = {"result":"error", "error": "You don't even have that item"}
    return ret 

def buyRelic(item):
    params = {"PHPSESSID": _sessionId, "iid": item}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/purchase/relic"
    return json.load(urllib.urlopen(url, query))

def buyWeapon(item):
    params = {"PHPSESSID": _sessionId, "iid": item}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/purchase/weapon"
    return json.load(urllib.urlopen(url, query))

def getProgress():
    params = {"PHPSESSID": _sessionId}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com/ajax/get_achievement_progress"
    return json.load(urllib.urlopen(url, query))

def getPlayerStats(player):
    params = {"PHPSESSID": _sessionId, "cid": player}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com/ajax/him"
    return json.load(urllib.urlopen(url, query))

def getPlayerPage(player):
    params = {"PHPSESSID": _sessionId}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//p/"+player
    #return json.load(urllib.urlopen(url, query))
    f = urllib.urlopen(url, query)
    contents = f.read()
    print contents
    f.close()

def assistAlly(ally, game, grade):
    params = {"PHPSESSID": _sessionId,
              "type": game,
              "grade": grade,
              "cid": ally,
              "text": ""}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/assist_ally"
    return json.load(urllib.urlopen(url, query))

def getTournamentPrizes():
    params = {"PHPSESSID": _sessionId}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/get_tournament_prizes"
    return json.load(urllib.urlopen(url, query))

def createTournament(tournamentType, tournamentSize): #same_level, open | 4,5,6
    params = {"PHPSESSID": _sessionId, "type": tournamentType, "size": tournamentSize}    
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/create_tournament"
    return json.load(urllib.urlopen(url, query))

def fightInTournament(tid):
    params = {"PHPSESSID": _sessionId, "tid": tid}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/tournament"
    return json.load(urllib.urlopen(url, query))

def getStage():
    params = {"PHPSESSID": _sessionId}
    query = urllib.urlencode(params)
    url = "http://kongregate.ninjawarz.brokenbulbstudios.com//ajax/stage"
    return json.load(urllib.urlopen(url, query))

#def clickGoldenCloud()
#http://kongregate.ninjawarz.brokenbulbstudios.com/ajax/golden_cloud

def prettyPrintJson(data):
    print json.dumps(data, sort_keys = True, indent = 3)

######################################################################
#init()
    
#r = getMyStats()
#r = getOpponents()
#r = fight(295)
#r = heal()
#r = train(417471)
#r = getProgress()
#r = sellItem(318)
#r = getPlayerPage("13734")
#r = assistAlly("13734", "3", "C")
#r = getTournamentPrizes()
#r = getStage()

#prettyPrintJson(r)




